# Copyright (c) 2008, Luke Freeman
# All rights reserved.

# Redistribution and use in source and binary forms, with or without modification, 
# are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice, this 
#      list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice, this 
#      list of conditions and the following disclaimer in the documentation and/or 
#      other materials provided with the distribution.
#    * Neither the name of Flag-Up nor the names of its contributors may 
#      be used to endorse or promote products derived from this software without specific 
#      prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.

import sys, os, re
import gconf

from base.base_util import *
from base.singleton import *


# globals
CONFIGURATION_ROOT = "/apps/flag-up"
configuration = gconf.client_get_default()

class Account(object):
    
    def __init__(self, name, mail_type, user, password, enabled):
        self.aid = None
        self.name = name
        self.mail_type = mail_type
        self.user = user
        self.password = password
        self.enabled = enabled
        
    

class AccountManager(Singleton):
    
    accounts = {}
    __first_time = True
    
    def __init__(self):

        if self.__first_time:
            # load all existing accounts
            acct_dirs = configuration.all_dirs(self.__full_conf_path("/accounts"))

            if len(acct_dirs) > 0:
                for acct_dir in acct_dirs:
                    acct = Account(
                        configuration.get_value("%s/name" % acct_dir),
                        configuration.get_value("%s/type" % acct_dir),
                        configuration.get_value("%s/user" % acct_dir),
                        configuration.get_value("%s/password" % acct_dir),
                        configuration.get_value("%s/enabled" % acct_dir)
                    )

                    acct_id = acct_dir.split("/").pop()
                    acct.aid = acct_id
                    
                    self.accounts[acct.name] = acct

            self.__first_time = False
            
    
    def __full_conf_path(self, conf_item):
        return "%s%s" % (CONFIGURATION_ROOT, conf_item)	
    
    def __get_next_acct_num(self):
        next_num = "1".rjust(8, "0")        # set the initial account number
        acct_dirs = configuration.all_dirs(self.__full_conf_path("/accounts"))
    
        if len(acct_dirs) > 0:
            next_num = max(acct_dirs).split("/").pop()
            next_num = str(int(next_num) + 1).rjust(8,"0")
            
        return next_num
            

    # create or update account configuration    
    def create_or_update_account(self, account):

        if account.aid == None:
            account.aid = self.__get_next_acct_num()

        # write to gconf
        account_folder = self.__full_conf_path("/accounts/%s" % account.aid)            
        configuration.set_value(("%s/name" % account_folder), account.name) 
        configuration.set_value(("%s/type" % account_folder), account.mail_type) 
        configuration.set_value(("%s/user" % account_folder), account.user) 
        configuration.set_value(("%s/password" % account_folder), account.password) 
        configuration.set_value(("%s/enabled" % account_folder), account.enabled) 
    
        self.accounts[account.name] = account
    
    
    def delete_account(self, name):
        account = self.accounts[name]
        account_folder = self.__full_conf_path("/accounts/%s" % account.aid)
        
        entries = configuration.all_entries(account_folder)
        for entry in entries:
            configuration.unset(entry.key)
                
        configuration.suggest_sync()
        
        del self.accounts[name]
    
    
	# checks to see if you can create the account    
    def can_create(self, name, mail_type, user, password):
		
		can_create = True
		message = "" 

		if self.accounts.has_key(name):
			can_create = False
			message = "The account name you specified is already in use. Account names must be unique."
		elif name == "" or mail_type == "" or user == "" or password == "":
			can_create = False
			message = "One or more of the account details was not filled out. All entries are mandatory."

		return can_create, message
        

    
    def get_account_from_name(self, name):
        return self.accounts[name]
    
        
    
    # account management methods
    def check_all_accounts(self):
        pass


    def check_single_account(self, name):
        pass
